﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Text;

namespace DNA.OpenAPI.Ping
{
    public class HttpClient
    {
        public string PostRequest(Uri url, string userAgent, int timeout, string formParameters)
        {
            if (formParameters == null)
                throw new ArgumentNullException("formParameters");

            ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.UserAgent = userAgent;
            request.Timeout = timeout;
            request.Method = "POST";
            request.ContentLength = formParameters.Length;
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            request.KeepAlive = true;

            using (StreamWriter myWriter = new StreamWriter(request.GetRequestStream()))
            {
                myWriter.Write(formParameters);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode < HttpStatusCode.OK && response.StatusCode >= HttpStatusCode.Ambiguous)
                throw new Exception(string.Format(response.StatusCode.ToString()));

            var responseText = string.Empty;
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
            {
                responseText = reader.ReadToEnd();
            }

            return responseText;
        }

        public Uri DiscoverPingBackServerUri(Uri url)
        {
            return null;
        }
    }
}